package com.blog.interceptor;

import com.blog.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author
 * @create 2018-06-07 11:23
 **/
public class Interceptor implements HandlerInterceptor {
    /**
     * 执行Handler方法之前执行
     * 用于身份认证、身份授权
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 获取请求的url
        String szURI = request.getRequestURI();

        // 如果是登录，就放行
        if (szURI.indexOf("login") >= 0 || szURI.indexOf("register")>=0) {
            return true;
        }

        // 判断session
        HttpSession session  = request.getSession();
        // 从session中取出用户身份信息
        User userInfo = (User)session.getAttribute("user");
        // session存在时，放行
        if (userInfo!=null) {
            return true;
        }


        // 执行这里表示用户身份需要认证，跳转登陆页面
        request.getRequestDispatcher("/WEB-INF/jsp/admin/login.jsp").forward(request, response);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
